package com.klxedu.ms.gateway;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import feign.RequestInterceptor;
import feign.RequestTemplate;

@Configuration
public class TenancyConfiguration {

	public static final String HOST_HEADER = "authService.HOST";
	private static ThreadLocal<String> tenancyLocal = new ThreadLocal<>();

	@Bean
	public TenancyFeignRequestInterceptor tenancyFeignInterceptor() {
		return new TenancyFeignRequestInterceptor();
	}

	@Bean
	public FilterRegistrationBean myCatSchemaSelector() {
		FilterRegistrationBean registration = new FilterRegistrationBean(new MyCatSchemaSelector());
		registration.addUrlPatterns("/*");
		registration.setName("myCatSchemaSelector");
		registration.setOrder(1);
		return registration;
	}

	public static class MyCatSchemaSelector extends OncePerRequestFilter {

		@Override
		protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
				FilterChain filterChain) throws ServletException, IOException {
			String header = request.getHeader(AuthServerConstants.HOST_HEADER_KEY);
			setTenancy(header);
			try {
				filterChain.doFilter(request, response);
			} finally {
				tenancyLocal.remove();
			}
		}

	}

	public static class TenancyFeignRequestInterceptor implements RequestInterceptor {

		@Override
		public void apply(RequestTemplate template) {
			template.header(HOST_HEADER, getTenancy());
		}

	}

	public static void setTenancy(String host) {
		if(host !=null && !"".equals(host)) {
			if(host.indexOf("://")!=-1) {
				host = host.substring(host.indexOf("://") + "://".length(), host.length());
			}
			if(host.indexOf(":")!=-1) {
				host = host.substring(0, host.lastIndexOf(":"));
			}
		} else {
			host = "";
		}
		tenancyLocal.set(host);
	}
	public static String getTenancy() {
		return tenancyLocal.get();
	}
}
